<template>
  <div style="height: 100%;padding-top: 3%;" @click="hideDetail()">
    <div class="sysleft syscamera syscamera2">
      <div class="parea">
        <!--<video src="rtsp://admin:Ecdatainfo.com@10.10.100.50:554/h264/ch1/main/av_stream" height="100%" width="100%" autoplay="autoplay">-->
        <!--</video>-->
        <!--<video id="test_video" controls autoplay height="100%" width="100%">-->
        <!--<source src="rtsp://admin:Ecdatainfo.com@10.10.100.50:554/h264/ch1/main/av_stream">-->
        <!--</video>-->
        <!--<embed type="application/x-vlc-plugin" pluginspage="http://www.videola.org"-->
        <!--width="640" height="480" id="vlc" version="VideoLAN.VLCPlugin.2" autoplay="yes" loop="no" target="rtsp://admin:Ecdatainfo.com@10.10.60.4:554/h264/ch1/main/av_stream" >-->
        <!--<div class="item">
          <div class="player">

          </div>
        </div>-->
        <video-player class="vjs-custom-skin"
                      ref="videoPlayer"
                      :options="playerOptions"
                      :playsinline="true"
                      @play="onPlayerPlay($event)"
                      @pause="onPlayerPause($event)"
                      @ended="onPlayerEnded($event)"
                      @loadeddata="onPlayerLoadeddata($event)"
                      @waiting="onPlayerWaiting($event)"
                      @playing="onPlayerPlaying($event)"
                      @timeupdate="onPlayerTimeupdate($event)"
                      @canplay="onPlayerCanplay($event)"
                      @canplaythrough="onPlayerCanplaythrough($event)"
                      @ready="playerReadied"
                      @statechanged="playerStateChanged($event)">
        </video-player>
      </div>
      <div class="cresult">
        <div class="left_bor"></div>
        <div class="right_bor"></div>
        <div class="titlearea">
          <div class="titlepos titleposr">
            <div class="title">
              <p class="chn">比对结果</p>
              <p class="eng">Comparing results</p>
            </div>
          </div>
        </div>
        <div class="pos_a">
          <div class="color_title">
            <img :src="colortitle"/>
            <div class="text" v-if="!withreturn">
              未搜索到匹配目标！
            </div>
            <div class="text" v-if="withreturn&&!returndanger">
              匹配度：<span>98%</span>
            </div>
            <div class="text" v-if="withreturn&&returndanger">
              该目标已加入黑名单！
            </div>
          </div>
        </div>
        <div class="main_c" :class="{blue_desc:withreturn&&!returndanger,red_desc:withreturn&&returndanger}">
          <div class="l_desc">
            <div class="desc_item">
              <div class="item_con onlyname">
                <div class="title2">
                  姓名
                </div>
                <div class="name" v-if="withreturn">
                  {{detail1name}}
                </div>
              </div>
            </div>
            <div class="desc_item" :class="{gender:detailPro1.gender!=1,gender2:detailPro1.gender==1}">
              <div class="item_con">
                <div class="title2">
                  性别
                </div>
                <div class="proname">
                  {{detailPro1.gender | genderFilter}}
                </div>
              </div>
            </div>
            <div class="desc_item">
              <div class="item_con onlyname">
                <div class="title2">
                  年龄
                </div>
                <div class="name">
                  {{detailPro1.age | ageFilter}}
                </div>
              </div>
            </div>
          </div>
          <div class="xb_face">
            <img :src="colormain" class="colorbg"/>
            <img :src="matchimg" v-if="matchimg" class="matchimg">
          </div>
          <div class="r_desc">
            <div class="desc_item" :class="{glasses:detailPro1.eyeglass!=0,glasses2:detailPro1.eyeglass==0}">
              <div class="item_con">
                <div class="title2">
                  眼镜
                </div>
                <div class="proname">
                  {{detailPro1.eyeglass | hasFilter}}
                </div>
              </div>
            </div>
            <div class="desc_item" :class="{hat:detailPro1.mask!=0,hat2:detailPro1.mask==0}">
              <div class="item_con">
                <div class="title2">
                  口罩
                </div>
                <div class="proname">
                  {{detailPro1.mask | hasFilter}}
                </div>
              </div>
            </div>
            <div class="desc_item" :class="{beard:detailPro1.beard!=0,beard2:detailPro1.beard==0}">
              <div class="item_con">
                <div class="title2">
                  胡须
                </div>
                <div class="proname">
                  {{detailPro1.beard | hasFilter}}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!--<img :src="matchimg" class="animateImg">-->
      <img :src="personimg" class="animateImg animateImg2" v-if="animateImg">
    </div>
    <div class="sysright syscamera syscamera2">
      <!--<div class="left_bor"></div>-->
      <!--<div class="right_bor"></div>-->
      <div class="mrecord">
        <div class="title">
          <p class="chn">比对记录</p>
          <p class="eng">Match record</p>
        </div>
        <div class="face-reco">
          <el-scrollbar>
            <ul>
              <li v-for="(item, index) in facelist" v-bind:key="item[0].id">
                <div class="datatime">{{item[item.length - 1].uploadTime | formatTime}}</div>
                <div class="dataitem" v-for="(item2, index2) in item" v-bind:key="item2.id"
                     @click.stop="forMore({index,index2},item2)"
                     :class="{success:clickIndex.index == index && clickIndex.index2 == index2,warning:!item2.staticFaceDb,danger:item2.staticFaceDb&&item2.faceBaseId==='blacklist'}">
                  <img :src="item2.imageidInFtp ? item2.imageidInFtp : nobodypng"/>
                  <p>{{item2.staticFaceDb ? item2.staticFaceDb.name : '无记录'}}</p>
                  <!--<p>张某某<span>男</span></p>-->
                </div>
              </li>
            </ul>
          </el-scrollbar>
          <!--<p class="noData" v-if="noData">-->
          <!--今日暂无人脸验证信息-->
          <!--</p>-->
          <div class="show_detail animated"
               :class="{fadeInRight:showdetail,fadeOutRight:!showdetail,loaded:detailloaded}">
            <div class="help_tri">
              <div class="detail_ava">
                <div class="ava_area">
                  <img :src="detailimg? detailimg:nobodypng"/>
                </div>
                <div class="matchedtext matchsuccess" v-if="detailType === 0">
                  <div>{{matchName}}</div>
                  <div>匹配结果:{{matchPoint}}%</div>
                </div>
                <div class="matchedtext matchdanger" v-if="detailType === 2">
                  <div>{{matchName}}</div>
                  <div>匹配结果:{{matchPoint}}%</div>
                </div>
                <div class="matchedtext matchnone" v-if="detailType === 1">
                  无记录
                </div>
              </div>
              <div class="detail_pro">
                <div class="detail_item detail_item1">
                  <div class="titleline"></div>
                  <div class="protitle">
                    特征
                  </div>
                  <ul class="proul">
                    <li>
                      年龄：{{detailPro2.age | ageFilter}}
                    </li>
                    <li>
                      性别：{{detailPro2.gender | genderFilter}}
                    </li>
                    <li>
                      人种：{{detailPro2.race | raceFilter}}
                    </li>
                    <li>
                      眼镜：{{detailPro2.eyeglass | hasFilter}}
                    </li>
                    <li>
                      胡须：{{detailPro2.beard | hasFilter}}
                    </li>
                  </ul>
                  <div style="clear: both;"></div>
                  <hr>
                  <ul class="proul">
                    <li>
                      张嘴：{{detailPro2.mouthOpen | hasFilter}}
                    </li>
                    <li>
                      睁眼：{{detailPro2.eyeOpen | hasFilter}}
                    </li>
                    <!--<li>-->
                    <!--眯眼：{{detailPro2.age}}-->
                    <!--</li>-->
                    <li>
                      口罩：{{detailPro2.mask | hasFilter}}
                    </li>
                    <li>
                      太阳镜：{{detailPro2.sunglass | hasFilter}}
                    </li>
                  </ul>
                  <div style="clear: both;"></div>
                </div>
                <!--<div class="detail_item detail_item2">
                  <div class="titleline"></div>
                  <div class="protitle">
                    指数
                  </div>
                  <div class="progress_area">
                    <div class="progress_item">
                      <div class="progress_num">
                        <div>
                          <ul>
                            <li class="pro_name">魅力</li>
                            <li class="pro_ratio">{{detailPro2.attractive}}%</li>
                          </ul>
                          <el-progress :percentage="detailPro2.attractive" :stroke-width="10"></el-progress>
                        </div>
                      </div>
                      <div class="progress_num">
                        <div>
                          <ul>
                            <li class="pro_name">微笑</li>
                            <li class="pro_ratio">{{detailPro2.smile}}%</li>
                          </ul>
                          <el-progress :percentage="detailPro2.smile" :stroke-width="10"></el-progress>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>-->
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import {videoPlayer} from 'vue-video-player'
  import 'video.js/dist/video-js.css'
  import videoJsFlash from 'videojs-flash'

  export default {
    data() {
      return {
        timeinterval: null,
        nobodypng: require('@/assets/img/nobody.png'),
        facelist: [], // 改造list
        facelist2: [], // 改造list
        orglist: [], // 原始list
        personimg: '',
        matchimg: '',
        animateImg: false,
        detailloaded: false,
        showdetail: false,
        detailPro1: {}, // 比对详情
        detail1name: '',
        detailPro2: {}, // 弹出详情
        detailType: '', // 0:正常 1:无记录 2:黑名单
        detailimg: '',
        matchPoint: '',
        matchName: '',
        withreturn: false,
        returndanger: false,
        clickIndex: {},
        colortitle: require('@/assets/img/yellowtitlesm.png'),
        colormain: require('@/assets/img/yellowmain.png'),
        redtitle: require('@/assets/img/redtitlesm.png'),
        redmain: require('@/assets/img/redmain.png'),
        yellowtitle: require('@/assets/img/yellowtitlesm.png'),
        yellowmain: require('@/assets/img/yellowmain.png'),
        bluetitle: require('@/assets/img/bluetitlesm.png'),
        bluemain: require('@/assets/img/bluemain.png'),
//        playerOptions: {
//          height: '360',
//          autoplay: true,
//          muted: true,
//          language: 'en',
//          playbackRates: [0.7, 1.0, 1.5, 2.0],
//          sources: [{
//            type: 'flv/mp4',
//            // mp4
//            src: 'http://10.10.10.226:8000/live/STREAM_NAME.flv'
//            // webm
//            // src: "https://cdn.theguardian.tv/webM/2015/07/20/150716YesMen_synd_768k_vp8.webm"
//          }],
//          poster: '/asserts/img/bag.png'
//        }
        playerOptions: {
          autoplay: true,
          controls: false,
          sourceOrder: true,
          aspectRatio: '16:7',
          flash: {hls: {withCredentials: false}},
          sources: [{
            type: 'rtmp/mp4',
//            src: 'http://vjs.zencdn.net/v/oceans.mp4'
            src: 'rtmp://10.10.10.226/live/STREAM_NAME'
          }],
          techOrder: ['flash'],
          poster: '/asserts/img/bag.png'
        }
      }
    },
    computed: {
      player() {
        return this.$refs.videoPlayer.player
      }
    },
    filters: {
      nameFilter: function (val) {
        let name = typeof (val) === 'undefined' ? '' : val
        return name
      },
      genderFilter: function (val) {
        let gender = typeof (val) === 'undefined' ? '' : val === 0 ? '男' : '女'
        return gender
      },
      raceFilter: function (val) {
        let race = val === 0 ? '黄' : val === 1 ? '黑' : val === 2 ? '白' : ''
        return race
      },
      hasFilter: function (val) {
        let hasOrnot = val === 0 ? '否' : val === 1 ? '是' : ''
        return hasOrnot
      },
      ageFilter: function (val) {
        let age = isNaN(val) ? '' : Math.ceil(val)
        return age
      },
      formatTime: function (val) {
        let time = ''
        if (val !== undefined) {
          var date = new Date(val)
          var hours = date.getHours()
          var minutes = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()
          var seconds = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds()
          time = hours + ':' + minutes + ':' + seconds
        }

        return time
      },
      dateFiter: function (val) {
        let datefilter = ''
        if (typeof (val) === 'string') {
          datefilter = val
        } else {
          let date = new Date(val)
          let month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : '0' + (date.getMonth() + 1)
          let day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate()
          datefilter = date.getFullYear() + '/' + month + '/' + day
        }
        return datefilter
      },
      timeFiter: function (val) {
        let timefilter = ''
        if (typeof (val) === 'string') {
          timefilter = val
        } else {
          let date = new Date(val)
          let hours = date.getHours() > 9 ? date.getHours() : '0' + date.getHours()
          let minuets = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()
          let seconds = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds()
          timefilter = hours + ':' + minuets + ':' + seconds
        }
        return timefilter
      }
    },
    methods: {
      // listen event
      onPlayerPlay(player) {
        console.log('player play!', player)
      },
      onPlayerPause(player) {
        // console.log('player pause!', player)
      },
      onPlayerEnded(player) {
        // console.log('player ended!', player)
      },
      onPlayerLoadeddata(player) {
        console.log('player Loadeddata!', player)
      },
      onPlayerWaiting(player) {
        // console.log('player Waiting!', player)
      },
      onPlayerPlaying(player) {
        // console.log('player Playing!', player)
      },
      onPlayerTimeupdate(player) {
        // console.log('player Timeupdate!', player.currentTime())
      },
      onPlayerCanplay(player) {
        console.log('player Canplay!', player)
      },
      onPlayerCanplaythrough(player) {
        // console.log('player Canplaythrough!', player)
      },

      // or listen state event
      playerStateChanged(playerCurrentState) {
        console.log('player current update state', playerCurrentState)
      },

      // player is ready
      playerReadied(player) {
        // seek to 10s
        console.log('example player 1 readied', player)
        player.currentTime(10)
        // console.log('example 01: the player is readied', player)
      },
      // isInsalledIEVLC() {
      //   try {
      //     var vlcObj = new ActiveXObject('VideoLAN.Vlcplugin.2')
      //     if (vlcObj != null) {
      //       return true
      //     }
      //   } catch (e) {
      //     return false
      //   }
      // },
      isInsalledFFVLC() {
        var numPlugins = navigator.plugins.length
        for (var i = 0; i < numPlugins; i++) {
          var plugin = navigator.plugins[i]
          if (plugin.name.indexOf('VideoLAN') > -1 || plugin.name.indexOf('VLC') > -1) {
            return true
          }
        }
        return false
      },
      handletimeInterval() {
        this.setTime()
        clearInterval(this.timeinterval)
        this.timeinterval = setInterval(() => {
          this.setTime()
        }, 1000)
      },
      setTime() {
        let time = new Date()
        let month = (time.getMonth() + 1) > 9 ? (time.getMonth() + 1) : '0' + (time.getMonth() + 1)
        let day = time.getDate() > 9 ? time.getDate() : '0' + time.getDate()
        let hours = time.getHours() > 9 ? time.getHours() : '0' + time.getHours()
        let minuets = time.getMinutes() > 9 ? time.getMinutes() : '0' + time.getMinutes()
        let seconds = time.getSeconds() > 9 ? time.getSeconds() : '0' + time.getSeconds()
        this.sysdate = time.getFullYear() + '-' + month + '-' + day
        this.systime = hours + ':' + minuets + ':' + seconds
      },
      forMore(index, item) {
        var vm = this
        if (!item.staticFaceDb) {
          vm.detailType = 1
        } else {
          vm.matchName = item.staticFaceDb.name
          vm.detailType = item.staticFaceDb.faceBaseId === 'blacklist' ? 2 : item.staticFaceDb.faceBaseId === 'whitelist' ? 0 : 1
        }
        if (item.score) {
          vm.matchPoint = (item.score * 100).toFixed(2)
        }
        // 获取库中头像
        vm.detailimg = (item.similarImageId && item.faceBaseId !== 'otherlist') ? 'http://10.10.10.69:9001/verify/face/gets?imageId=' + item.similarImageId : vm.nobodypng
        // 获取特征
        var imagePath = item.imageidInFtp.indexOf('?fileName=') > -1 ? item.imageidInFtp.split('?fileName=')[1] : item.imageidInFtp
        if (vm.clickIndex.index === index.index && vm.clickIndex.index2 === index.index2) {
          vm.clickIndex = {}
          vm.showdetail = false
        } else {
          vm.clickIndex = index
          vm.detailloaded = true
          if (vm.showdetail === false) {
            vm.showdetail = true
          }
          vm.axios.get(vm.FSA + '/face/faceAttribute?imagePath=' + imagePath).then(function (response) {
            vm.detailPro2 = response.data.data
            console.log(vm.detailPro2)
          }).catch(function (error) {
            console.log(error)
          })
        }
      },
      hideDetail() {
        this.clickIndex = {}
        this.showdetail = false
      },
      getLatest() {
        var vm = this
        var latestid = vm.facelist2.length > 0 ? vm.facelist2[vm.facelist2.length - 1].id : vm.facelist.length > 0 ? vm.facelist[0][0].id : 0
        vm.axios.get(vm.FSA + '/face/latestVisitor?id=' + latestid).then(function (res) {
          // 将每次获取的数据concat到facelist2中
          if (res.data.data && res.data.data.length > 0) {
            vm.facelist2.push(...res.data.data)
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      showLatest() {
        var vm = this
        // 每隔三秒赋新值
        setInterval(() => {
          vm.animateImg = false
          if (vm.facelist2.length > 0 && ((vm.facelist.length > 0 && vm.facelist[0][0].id !== vm.facelist2[0].id) || vm.facelist.length === 0)) {
            vm.personimg = vm.FSA + '/face/downloadftpPic?fileName=' + vm.facelist2[0].imageidInFtp
            // 获取库中头像
            vm.matchimg = vm.facelist2[0].similarImageId ? 'http://10.10.10.69:9001/verify/face/gets?imageId=' + vm.facelist2[0].similarImageId : ''
            vm.shotdate = vm.facelist2[0].uploadTime
            vm.axios.get(vm.FSA + '/face/faceAttribute?imagePath=' + vm.facelist2[0].imageidInFtp).then(function (response) {
              vm.detailPro1 = response.data.data
              if (typeof (vm.facelist2[0].staticFaceDb) === 'undefined') {
                vm.colortitle = vm.yellowtitle
                vm.colormain = vm.yellowmain
                vm.withreturn = false
                vm.returndanger = false
              } else {
                vm.colortitle = vm.facelist2[0].staticFaceDb.faceBaseId === 'blacklist' ? vm.redtitle : vm.bluetitle
                vm.colormain = vm.facelist2[0].staticFaceDb.faceBaseId === 'blacklist' ? vm.redmain : vm.bluemain
                vm.returndanger = vm.facelist2[0].staticFaceDb.faceBaseId === 'blacklist'
                vm.withreturn = true
                vm.detail1name = vm.facelist2[0].staticFaceDb.name
              }
            }).catch(function (error) {
              console.log(error)
            })
            var animateTimeout = setTimeout(() => {
              vm.animateImg = true
              clearTimeout(animateTimeout)
            }, 500)
            // push到facelist中并从facelist2中删除
            setTimeout(() => {
              vm.facelist2[0].imageidInFtp = vm.FSA + '/face/downloadftpPic?fileName=' + vm.facelist2[0].imageidInFtp
              if (vm.facelist[0] && vm.facelist[0].length > 0 && vm.facelist2[0].uploadTime - vm.facelist[0][vm.facelist[0].length - 1].uploadTime < 10000) {
                vm.facelist[0].unshift(vm.facelist2[0])
              } else {
                vm.facelist.unshift([vm.facelist2[0]])
              }
              vm.facelist2.shift()
              vm.animateImg = false
            }, 2000)
          }
//          else {
//            clearInterval(faceIntervel)
//          }
        }, 3000)
      }
    },
    mounted() {
      var vm = this
      vm.handletimeInterval()
      // 获取初始list
      vm.axios.get(vm.FSA + '/log/getLatestLogs?num=200').then(function (response) {
        vm.orglist = response.data.data
        if (vm.orglist && vm.orglist.length > 0) {
          var list = []
          var listItem = []
          var firstTime = vm.orglist[vm.orglist.length - 1].uploadTime
          for (var idx = vm.orglist.length - 1; idx >= 0; idx--) {
            vm.orglist[idx].imageidInFtp = vm.FSA + '/face/downloadftpPic?fileName=' + vm.orglist[idx].imageidInFtp
            if (vm.orglist[idx].uploadTime <= firstTime + 10000) {
              listItem.unshift(vm.orglist[idx])
            } else {
              list.unshift(listItem)
              listItem = []
              firstTime = vm.orglist[idx].uploadTime
              listItem.unshift(vm.orglist[idx])
            }
          }
          list.unshift(listItem)
          vm.facelist = list
          // 初始比对结果
          vm.personimg = vm.facelist[0][0].imageidInFtp
          // 获取库中头像
          vm.matchimg = vm.facelist[0][0].similarImageId ? 'http://10.10.10.69:9001/verify/face/gets?imageId=' + vm.facelist[0][0].similarImageId : ''
          vm.shotdate = vm.facelist[0][0].uploadTime
          var imagePath = vm.personimg.split('?fileName=')[1]
          vm.axios.get(vm.FSA + '/face/faceAttribute?imagePath=' + imagePath).then(function (response) {
            vm.detailPro1 = response.data.data
            vm.detail1name = vm.facelist[0][0].staticFaceDb ? (vm.facelist[0][0].staticFaceDb.name ? vm.facelist[0][0].staticFaceDb.name : '') : ''
          }).catch(function (error) {
            console.log(error)
          })
          if (typeof (vm.facelist[0][0].staticFaceDb) === 'undefined') {
            vm.colortitle = vm.yellowtitle
            vm.colormain = vm.yellowmain
            vm.withreturn = false
            vm.returndanger = false
          } else {
            vm.colortitle = vm.facelist[0][0].staticFaceDb.faceBaseId === 'blacklist' ? vm.redtitle : vm.bluetitle
            vm.colormain = vm.facelist[0][0].staticFaceDb.faceBaseId === 'blacklist' ? vm.redmain : vm.bluemain
            vm.returndanger = vm.facelist[0][0].staticFaceDb.faceBaseId === 'blacklist'
            vm.withreturn = true
            vm.detail1name = vm.facelist[0][0].staticFaceDb.name
          }
        }
        // 获取最近数据
        vm.getLatest()
        setInterval(() => {
          vm.getLatest()
        }, 1000)
        vm.showLatest()
      }).catch(function (error) {
        console.log(error)
      })
      /* ---------------------------------------------- */
      var userAgent = navigator.userAgent
      // if (window.ActiveXObject || 'ActiveXObject' in window) {
      //   if (vm.isInsalledIEVLC()) {
      //     alert('已装VLC插件')
      //   } else {
      //     alert('未装VLC插件,请先安装插件')
      //     // location.href="http://download.videolan.org/pub/videolan/vlc/2.2.1/";
      //   }
      // } else
      if (userAgent.toUpperCase().indexOf('Firefox') !== -1) {
        if (vm.isInsalledFFVLC()) {
          alert('已装VLC插件')
        } else {
          alert('未装VLC插件')
          // location.href="http://download.videolan.org/pub/videolan/vlc/2.2.1/";
        }
      }
//      this.handleInterval()
//      this.colortitle = this.redtitle

      // console.log('this is current player instance object', this.player)
      setTimeout(() => {
        console.log('dynamic change options', this.player)
        // change src
        // this.playerOptions.sources[0].src = 'https://cdn.theguardian.tv/webM/2015/07/20/150716YesMen_synd_768k_vp8.webm';

        // change item
        // this.$set(this.playerOptions.sources, 0, {
        //   type: "video/mp4",
        //   src: 'https://cdn.theguardian.tv/webM/2015/07/20/150716YesMen_synd_768k_vp8.webm',
        // })

        // change array
        // this.playerOptions.sources = [{
        //   type: "video/mp4",
        //   src: 'https://cdn.theguardian.tv/webM/2015/07/20/150716YesMen_synd_768k_vp8.webm',
        // }]
//        this.player.muted(false)
      }, 5000)
    },
    components: {
      videoPlayer,
      videoJsFlash
    }
  }
</script>
